package com.learning.security.core.filter;

import com.learning.security.api.AdminOAuth2TokenApi;
import com.learning.security.api.dto.AdminOAuth2AccessTokenCheckRespDTO;
import com.learning.security.service.AdminRoleService;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.Objects;

public class TokenAuthenticationFilter extends OncePerRequestFilter {
    private final AdminOAuth2TokenApi adminOAuth2TokenApi;
    private final AdminRoleService adminRoleService;

    public TokenAuthenticationFilter(AdminOAuth2TokenApi adminOAuth2TokenApi, AdminRoleService adminRoleService) {
        this.adminOAuth2TokenApi = adminOAuth2TokenApi;
        this.adminRoleService = adminRoleService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        if ("/admin/system/login".equalsIgnoreCase(requestURI)) {
            filterChain.doFilter(request, response);
            return;
        }
        String token = request.getHeader("Authorization");
        if (StringUtils.hasText(token)) {
            LoginUser loginUser = buildLoginUserByToken(token);
            if (Objects.nonNull(loginUser)) {
                // 创建 UsernamePasswordAuthenticationToken 对象
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                        loginUser, null, buildGrantedAuthority(loginUser.getId()));
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }

        filterChain.doFilter(request, response);
    }

    private Collection<? extends GrantedAuthority> buildGrantedAuthority(Long userId) {
        return adminRoleService.buildGrantedAuthority(userId);
    }

    private LoginUser buildLoginUserByToken(String token) {
        AdminOAuth2AccessTokenCheckRespDTO accessToken = adminOAuth2TokenApi.checkAccessToken(token);
        if (Objects.isNull(accessToken)) {
            return null;
        }
        return new LoginUser().setId(accessToken.getUserId())
                .setUserType(accessToken.getUserType())
                .setInfo(accessToken.getUserInfo())
                .setTenantId(accessToken.getTenantId())
                .setScopes(accessToken.getScopes());
    }
}
